package org.xx.armory.spring5.mvc;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.SQLException;
import java.util.Date;

import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.UNAUTHORIZED;
import static org.xx.armory.spring5.mvc.WebUtils.throwHttpClientException;

/**
 * 主动异常触发器。
 * <p>用于主动触发异常，检测系统的异常拦截机制是否正常。</p>
 */
@Controller
@RequestMapping("/diagnosis")
public class ActiveBreakerController {
    @GetMapping("/active-breaker")
    public ResponseEntity<?> execute(
            @RequestParam(name = "type",
                          defaultValue = "1") int type
    )
            throws Exception {
        final var message = "Active-breaker was triggered at " + new Date();
        switch (type) {
            case 1:
                throw new RuntimeException(message);
            case 2:
                throw new SQLException(message, "Mock sql error", 0x77);
            case 3:
                throw new BusinessLogicException(2, message)
                        .addExtra("count", 2)
                        .addExtra("cause", "Mock");
            case 4:
                throwHttpClientException(BAD_REQUEST);
            case 5:
                throwHttpClientException(UNAUTHORIZED);
            default:
                throw new IllegalArgumentException("Unknown type: " + type);
        }
    }
}
